import { tophubAttachmentPreview } from '@/services/api/api-tophub-attachment';
import { selectTophubOperate, updateTophubState } from '@/services/api/api-tophub-operate';

import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  CloseCircleTwoTone,
  DownloadOutlined,
} from '@ant-design/icons';
import { ActionType, DrawerForm, ModalForm, ProFormTextArea } from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import {
  Alert,
  Button,
  Descriptions,
  Divider,
  Flex,
  Image,
  message,
  Space,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import DetailsOperateEdit from './DetailsOperateEdit';
import DetailsOperateState from './DetailsOperateState';
interface DetailsOperateProps {
  dom: React.ReactNode;
  data: TophubOperateData.OperatePage;
  onRefurbish: () => void;
}

const DetailsOperate: React.FC<DetailsOperateProps> = ({ dom, data, onRefurbish }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const [loading, setLoading] = useState(false);

  const [open, setOpenState] = useState(false);

  const [details, setDetailsState] = useState<TophubOperateData.OperateSelect>();

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);

  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });

  const iframeRef = useRef(null);

  /**
   * 加载 选题计划详情
   * @param key
   */
  const loadTophubRecordDetails = async () => {
    setLoading(true);
    try {
      const response = await selectTophubOperate({
        id: data.id,
      });

      if (response.code == 0) {
        setDetailsState(response.data);
        setLoading(false);
      }
    } catch (error) {}
  };

  const submitter = () => {
    if (!details) {
      return false;
    }

    if (access.热搜热榜x配置x管理员) {
      if (details?.state == 1) {
        //待申请
        return {
          render: (props, dom) => {
            return [
              <ModalForm
                key={'modal_form_record_state_discard'}
                title={
                  <>
                    <CloseCircleTwoTone
                      style={{
                        marginRight: 8,
                      }}
                      twoToneColor="#FF4D4F"
                    />
                    退回
                  </>
                }
                trigger={
                  <Button
                    key="button_record_state_discard"
                    icon={<CloseCircleOutlined />}
                    type="primary"
                    danger
                  >
                    退回
                  </Button>
                }
                autoFocusFirstInput
                modalProps={{
                  width: 400,
                  // bodyStyle: { textAlign: 'center' },
                  destroyOnClose: true,
                  onCancel: () => console.log('run'),
                }}
                submitTimeout={2000}
                submitter={{
                  submitButtonProps: {
                    type: 'primary',
                    style: { background: '#FF4D4F' },
                  },
                }}
                onFinish={async (values) => {
                  const response = await updateTophubState({
                    id: data.id,
                    state: 2, //退回
                    ...values,
                  });

                  if (response.code == 0) {
                    onRefurbish();
                    setOpenState(false);
                    return true;
                  }
                }}
              >
                <Typography.Paragraph>
                  <blockquote>退回，以下是意见</blockquote>
                </Typography.Paragraph>
                <ProFormTextArea
                  width="xl"
                  name="content"
                  fieldProps={{
                    rows: 6,
                    allowClear: true,
                    maxLength: 50000,
                    placeholder: '请输入退回原因（支持换行输入）',
                    showCount: true,
                  }}
                  rules={[{ required: true, message: '请输入退回原因' }]}
                />
              </ModalForm>,
              <ModalForm
                key={'modal_form_record_state_release'}
                title={
                  <>
                    <CheckCircleOutlined
                      style={{
                        marginRight: 8,
                        color: '#108ee9',
                      }}
                    />
                    发布
                  </>
                }
                trigger={
                  <Button
                    key="button_record_state_release"
                    icon={<CheckCircleOutlined />}
                    type="primary"
                  >
                    发布
                  </Button>
                }
                autoFocusFirstInput
                modalProps={{
                  width: 400,
                  // bodyStyle: { textAlign: 'center' },
                  destroyOnClose: true,
                  onCancel: () => console.log('run'),
                }}
                submitTimeout={2000}
                submitter={{
                  submitButtonProps: {
                    type: 'primary',
                  },
                }}
                onFinish={async (values) => {
                  const response = await updateTophubState({
                    id: data.id,
                    state: 3, //发布
                    ...values,
                  });

                  if (response.code == 0) {
                    onRefurbish();
                    setOpenState(false);
                    return true;
                  }
                }}
              >
                <Typography.Paragraph>
                  <blockquote>确认，以下是意见</blockquote>
                </Typography.Paragraph>
                <ProFormTextArea
                  width="xl"
                  name="content"
                  fieldProps={{
                    rows: 6,
                    allowClear: true,
                    maxLength: 50000,
                    placeholder: '请输入确认原因（支持换行输入）',
                    showCount: true,
                  }}
                />
              </ModalForm>,
            ];
          },
        };
      } else if (details?.state == 1) {
        //退回、发布
        return false;
      } else {
        //退回、发布
        return false;
      }
    }

    if (access.热搜热榜x配置x运营员) {
      if (details?.state == 1) {
        //待申请
        return {
          render: (props, dom) => {
            return [
              <ModalForm
                key={'modal_form_record_state_discard'}
                title={
                  <>
                    <CloseCircleTwoTone
                      style={{
                        marginRight: 8,
                      }}
                      twoToneColor="#FF4D4F"
                    />
                    撤回
                  </>
                }
                trigger={
                  <Button
                    key="button_record_state_discard"
                    icon={<CloseCircleOutlined />}
                    type="primary"
                    danger
                  >
                    撤回
                  </Button>
                }
                autoFocusFirstInput
                modalProps={{
                  width: 400,
                  // bodyStyle: { textAlign: 'center' },
                  destroyOnClose: true,
                  onCancel: () => console.log('run'),
                }}
                submitTimeout={2000}
                submitter={{
                  submitButtonProps: {
                    type: 'primary',
                    style: { background: '#FF4D4F' },
                  },
                }}
                onFinish={async (values) => {
                  const response = await updateTophubState({
                    id: data.id,
                    state: 2, //撤回
                    ...values,
                  });

                  if (response.code == 0) {
                    onRefurbish();
                    setOpenState(false);
                    return true;
                  }
                }}
              >
                <Typography.Paragraph>
                  <blockquote>撤回，以下是意见</blockquote>
                </Typography.Paragraph>
                <ProFormTextArea
                  width="xl"
                  name="content"
                  fieldProps={{
                    rows: 6,
                    allowClear: true,
                    maxLength: 50000,
                    placeholder: '请输入撤回原因（支持换行输入）',
                    showCount: true,
                  }}
                  rules={[{ required: true, message: '请输入撤回原因' }]}
                />
              </ModalForm>,
            ];
          },
        };
      } else if (details?.state == 2) {
        //退回
        return {
          render: (props, dom) => {
            return [
              <DetailsOperateEdit
                data={details}
                onRefurbish={function (): void {
                  loadTophubRecordDetails();
                }}
                onOpenChange={function (visible: boolean): void {}}
              />,
              <ModalForm
                key={'modal_form_record_state_release'}
                title={
                  <>
                    <CheckCircleOutlined
                      style={{
                        marginRight: 8,
                        color: '#108ee9',
                      }}
                    />
                    提交
                  </>
                }
                trigger={
                  <Button
                    key="button_record_state_release"
                    icon={<CheckCircleOutlined />}
                    type="primary"
                  >
                    再次提交
                  </Button>
                }
                autoFocusFirstInput
                modalProps={{
                  width: 400,
                  // bodyStyle: { textAlign: 'center' },
                  destroyOnClose: true,
                  onCancel: () => console.log('run'),
                }}
                submitTimeout={2000}
                submitter={{
                  submitButtonProps: {
                    type: 'primary',
                  },
                }}
                onFinish={async (values) => {
                  const response = await updateTophubState({
                    id: data.id,
                    state: 1, //提交
                    ...values,
                  });

                  if (response.code == 0) {
                    onRefurbish();
                    setOpenState(false);
                    return true;
                  }
                }}
              >
                <Typography.Paragraph>
                  <blockquote>确认，以下是意见</blockquote>
                </Typography.Paragraph>
                <ProFormTextArea
                  width="xl"
                  name="content"
                  fieldProps={{
                    rows: 6,
                    allowClear: true,
                    maxLength: 50000,
                    placeholder: '请输入确认原因（支持换行输入）',
                    showCount: true,
                  }}
                />
              </ModalForm>,
            ];
          },
        };
      } else {
        //发布
        return false;
      }
    }

    return false;
  };
  return (
    <DrawerForm
      title={
        <>
          <Tag color={details?.hotIsCity == 0 ? 'error' : 'gold'}>
            {details?.hotIsCity == 0 ? '全国' : '重庆'}：{details?.hotMaxTopIndex}
          </Tag>
          {details?.hotName}
        </>
      }
      trigger={<a>{dom}</a>}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
        width: 650,
        extra: [
          details?.insertType == 2 && (
            <DetailsOperateState data={details} onRefurbish={function (): void {}} />
          ),
        ],
      }}
      open={open}
      onOpenChange={async (visible) => {
        setOpenState(visible);
        if (visible) {
          loadTophubRecordDetails();
        } else {
          onRefurbish();
        }
      }}
      submitter={submitter()}
      onFinish={async (values) => {
        console.log(values);
      }}
    >
      <Descriptions column={3}>
        <Descriptions.Item label="状态">
          {details?.state == 1 ? (
            <Tag color="blue">待审核</Tag>
          ) : details?.state == 2 ? (
            <Tag color="red">拒绝</Tag>
          ) : (
            <Tag color="green">发布</Tag>
          )}
        </Descriptions.Item>
        <Descriptions.Item label="收录">
          {details?.insertType == 1 ? '自动收录' : '手工录入'}
        </Descriptions.Item>
        <Descriptions.Item label="类型">
          {details?.recordType == 1 ? '热搜' : '微信'}
        </Descriptions.Item>
      </Descriptions>
      {details?.state == 3 && details?.stateContent && (
        <Typography.Paragraph>
          <blockquote>{details?.stateContent}</blockquote>
        </Typography.Paragraph>
      )}
      <Divider />

      <Descriptions column={2}>
        <Descriptions.Item span={2} label="词条">
          {details?.hotName}
        </Descriptions.Item>
      </Descriptions>

      <Descriptions column={2}>
        <Descriptions.Item label="平台">
          {details?.hotType == 1 ? '微博' : details?.hotType == 2 ? '抖音' : '头条'}
        </Descriptions.Item>
        <Descriptions.Item label="最高排名">{details?.hotMaxTopIndex}</Descriptions.Item>
      </Descriptions>

      <Descriptions column={2}>
        <Descriptions.Item label="账号">{details?.datahubSourceName}</Descriptions.Item>
        <Descriptions.Item label="媒体">{details?.datahubLevelName}</Descriptions.Item>
        <Descriptions.Item label="采录时间">{details?.hotInsertTime}</Descriptions.Item>
      </Descriptions>

      {details?.insertType == 1 ? (
        <></>
      ) : (
        <>
          <Divider />
          <Descriptions>
            <Descriptions.Item label="创建人">{details?.createdAccountName}</Descriptions.Item>
          </Descriptions>
          {details?.sources && (
            <Descriptions column={1}>
              <Descriptions.Item label="该词条其他关联账号">
                <Space size={[8, 16]} wrap>
                  {details?.sources?.map((item) => (
                    <Tag>{item.name}</Tag>
                  ))}
                </Space>
              </Descriptions.Item>
            </Descriptions>
          )}
          {details?.remarks && (
            <Typography.Paragraph>
              <blockquote>{details?.remarks}</blockquote>
            </Typography.Paragraph>
          )}

          {details?.attachments && (
            <div
              style={{
                marginTop: 10,
              }}
            >
              <Flex justify="space-between" align="center">
                <span>附件：</span>
                <Button
                  type="primary"
                  key="import"
                  size="small"
                  icon={<DownloadOutlined />}
                  onClick={() => {
                    details?.attachments?.forEach(function (item) {
                      window.open(item.content, '_blank');
                    });
                  }}
                >
                  全部下载
                </Button>
              </Flex>
              <Upload
                listType="picture"
                multiple
                fileList={details?.attachments?.map((item) => {
                  return {
                    uid: item.id,
                    name: item.name,
                    url: item.content,
                    mimeType: item.mimeType,
                    status: 'done',
                  };
                })}
                showUploadList={{
                  downloadIcon: (
                    <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                      <DownloadOutlined
                        style={{
                          marginRight: '10px',
                        }}
                      />
                      点击下载
                    </div>
                  ),
                  showRemoveIcon: false,
                  showDownloadIcon: true,
                }}
                onPreview={async (file: UploadFile) => {
                  setPreviewData({
                    id: file.uid,
                    name: file.name,
                    mimeType: file.mimeType,
                    url: encodeURI(file.url),
                  });
                  setPreviewOpen(true);
                }}
              />
              <DrawerForm
                title={previewData?.name}
                drawerProps={{
                  width: 900,
                  destroyOnClose: true,
                }}
                open={previewOpen}
                onOpenChange={async (visible) => {
                  if (visible) {
                    if (
                      previewData?.mimeType !== null &&
                      previewData?.mimeType?.indexOf('image') > -1
                    ) {
                      //图片预览
                    } else {
                      setPreviewLoading(true);

                      const response = await tophubAttachmentPreview({
                        id: previewData?.id,
                      });

                      if (response.code === 0) {
                        setPreviewOnlineUrl(response.data);
                      } else {
                        message.error('暂时无法预览');
                        setPreviewLoading(false);
                      }
                    }
                  } else {
                    setPreviewOpen(false);
                    setPreviewData(undefined);
                    setPreviewOnlineUrl(undefined);
                  }
                }}
                submitter={{
                  searchConfig: {
                    submitText: '下载',
                  },
                }}
                onFinish={async (values) => {
                  window.open(previewData?.url, '_blank');
                }}
              >
                <Alert
                  style={{
                    marginBottom: 20,
                  }}
                  message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                  type="warning"
                  showIcon
                />
                {previewData?.mimeType !== null && previewData?.mimeType?.indexOf('image') > -1 ? (
                  <Image width="100%" src={previewData?.url} />
                ) : (
                  <Spin spinning={previewLoading}>
                    <iframe
                      ref={iframeRef}
                      src={previewOnlineUrl}
                      height={windowSize.innerHeight - 220}
                      width="100%"
                      frameBorder="0"
                      // scrolling="false"
                      allowFullScreen={true}
                      // scrolling={'no'}
                    />
                  </Spin>
                )}
              </DrawerForm>
            </div>
          )}
        </>
      )}
    </DrawerForm>
  );
};
export default DetailsOperate;
